using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace App
{
    class BusyIcon : PictureBox
    {
        Timer m_Timer;
        int m_Tick = 0;
        bool m_Stop = false;
        bool m_Hover = false;
        public BusyIcon()
        {
            m_Timer = new Timer();
            m_Timer.Interval = 50;
            m_Timer.Tick += new EventHandler(timer1_Tick);
            this.Paint += new PaintEventHandler(Busy_Paint);
            this.Width = 24;
            this.Height = 24;
            this.BackColor = Color.Transparent;
        }

        protected override void OnMouseHover(EventArgs e)
        {
            m_Hover = true;
            base.OnMouseHover(e);
            Invalidate();
        }

        protected override void OnMouseLeave(EventArgs e)
        {
            m_Hover = false;
            base.OnMouseLeave(e);
            Invalidate();
        }

        void Busy_Paint(object sender, PaintEventArgs e)
        {
            if (e.ClipRectangle.Width == 0 || e.ClipRectangle.Height == 0)
                return;
            //Draw Hover
            Rectangle rect = new Rectangle(0, 0, this.Width - 1, this.Height - 1);
            if (m_Hover)
                DrawHelper.RenderSelection(e.Graphics, rect, 1f, false);
            //Draw Animate
            Image img = Properties.Resources.Logo24;
            Rectangle rectImg = new Rectangle(24 * m_Tick, 0, 24, 24);
            e.Graphics.DrawImage(img, new Rectangle(0, 0, 24, 24), rectImg, GraphicsUnit.Pixel);
        }

        void timer1_Tick(object sender, EventArgs e)
        {
            Invalidate();
            if (m_Tick == 23)
            {
                m_Tick = 0;
            }
            else
            {
                m_Tick++;
            }
            if (m_Stop && m_Tick == 0)
            {
                m_Timer.Enabled = false;
            }
        }

        public bool IsBusy
        {
            get
            {
                return m_Timer.Enabled;
            }
            set
            {
                if (value)
                {
                    m_Tick = 0;
                    m_Stop = false;
                    m_Timer.Enabled = value;
                }
                else
                {
                    m_Stop = true;
                }
            }
        }
    }
}
